import { defineStore } from 'pinia'

export const useNodesStore = defineStore('notesStore', {
  state() {
    return {
      notes: [
        {
          id: '001',
          content: '我学会了Vuex的三个重要组成部门：state(getters), mutations, actions'
        },
        {
          id: '002',
          content: 'getters如何传参——在getters函数里返回一个函数，这个函数是可以接收组件传递过来的参数的。'
        },
      ],

      msg: 'abc'
    }
  },

  actions: {
    add (note) {
      this.notes.unshift(note)
    },

    edit(id) {

      this.notes
    },

    changeMsg() {
      this.msg = 'aaabbbccc'
    },  
    
    deleteNote(id) {
      // 方法一：
      // const newNotes = state.notes.filter(note => note.id !== id)
      // state.notes = newNotes

      // 方法二：
      const index = this.notes.findIndex(note => note.id === parseInt(id))
      this.notes.splice(index, 1)
    },

    saveNote(payload) {
      const { id, note } = payload
      const obj = this.notes.find(n => n.id === parseInt(id))
      obj.content = note
    }
  },
  
  getters: {
    contentById() {
      return (id) => {
        const note = this.notes.find(note => note.id === parseInt(id))
        return note.content
      }
    },

    itemsCount() {
      return this.notes.length
    },

    charactorCount() {
      return this.notes.reduce((sum, note) => {
        sum += note.content.length
        return sum
      }, 0)
    }
  }
})